Merge "rdbms: make LBFactory close/rollback dangling handles like LoadBalancer"
[lhc/web/wiklou.git] / includes / libs / rdbms / database / DatabaseSqlite.php
1 <?php
2 /**
3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Database
23 */
24 namespace Wikimedia\Rdbms;
25
26 use NullLockManager;
27 use PDO;
28 use PDOException;
29 use Exception;
30 use LockManager;
31 use FSLockManager;
32 use RuntimeException;
33 use stdClass;
34
35 /**
36 * @ingroup Database
37 */
38 class DatabaseSqlite extends Database {
39 /** @var string|null Directory for SQLite database files listed under their DB name */
40 protected $dbDir;
41 /** @var string|null Explicit path for the SQLite database file */
42 protected $dbPath;
43 /** @var string Transaction mode */
44 protected $trxMode;
45
46 /** @var int The number of rows affected as an integer */
47 protected $lastAffectedRowCount;
48 /** @var resource */
49 protected $lastResultHandle;
50
51 /** @var PDO */
52 protected $conn;
53
54 /** @var FSLockManager (hopefully on the same server as the DB) */
55 protected $lockMgr;
56
57 /** @var array List of shared database already attached to this connection */
58 private $alreadyAttached = [];
59
60 /** @var bool Whether full text is enabled */
61 private static $fulltextEnabled = null;
62
63 /** @var string[] See https://www.sqlite.org/lang_transaction.html */
64 private static $VALID_TRX_MODES = [ '', 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ];
65
66 /**
67 * Additional params include:
68 * - dbDirectory : directory containing the DB and the lock file directory
69 * - dbFilePath : use this to force the path of the DB file
70 * - trxMode : one of (deferred, immediate, exclusive)
71 * @param array $params
72 */
73 public function __construct( array $params ) {
74 if ( isset( $params['dbFilePath'] ) ) {
75 $this->dbPath = $params['dbFilePath'];
76 if ( !strlen( $params['dbname'] ) ) {
77 $params['dbname'] = self::generateDatabaseName( $this->dbPath );
78 }
79 } elseif ( isset( $params['dbDirectory'] ) ) {
80 $this->dbDir = $params['dbDirectory'];
81 }
82
83 parent::__construct( $params );
84
85 $this->trxMode = strtoupper( $params['trxMode'] ?? '' );
86
87 $lockDirectory = $this->getLockFileDirectory();
88 if ( $lockDirectory !== null ) {
89 $this->lockMgr = new FSLockManager( [
90 'domain' => $this->getDomainID(),
91 'lockDirectory' => $lockDirectory
92 ] );
93 } else {
94 $this->lockMgr = new NullLockManager( [ 'domain' => $this->getDomainID() ] );
95 }
96 }
97
98 protected static function getAttributes() {
99 return [
100 self::ATTR_DB_IS_FILE => true,
101 self::ATTR_DB_LEVEL_LOCKING => true
102 ];
103 }
104
105 /**
106 * @param string $filename
107 * @param array $p Options map; supports:
108 * - flags : (same as __construct counterpart)
109 * - trxMode : (same as __construct counterpart)
110 * - dbDirectory : (same as __construct counterpart)
111 * @return DatabaseSqlite
112 * @since 1.25
113 */
114 public static function newStandaloneInstance( $filename, array $p = [] ) {
115 $p['dbFilePath'] = $filename;
116 $p['schema'] = null;
117 $p['tablePrefix'] = '';
118 /** @var DatabaseSqlite $db */
119 $db = Database::factory( 'sqlite', $p );
120
121 return $db;
122 }
123
124 /**
125 * @return string
126 */
127 public function getType() {
128 return 'sqlite';
129 }
130
131 protected function open( $server, $user, $pass, $dbName, $schema, $tablePrefix ) {
132 $this->close();
133
134 // Note that for SQLite, $server, $user, and $pass are ignored
135
136 if ( $schema !== null ) {
137 throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
138 }
139
140 if ( $this->dbPath !== null ) {
141 $path = $this->dbPath;
142 } elseif ( $this->dbDir !== null ) {
143 $path = self::generateFileName( $this->dbDir, $dbName );
144 } else {
145 throw $this->newExceptionAfterConnectError( "DB path or directory required" );
146 }
147
148 // Check if the database file already exists but is non-readable
149 if (
150 !self::isProcessMemoryPath( $path ) &&
151 file_exists( $path ) &&
152 !is_readable( $path )
153 ) {
154 throw $this->newExceptionAfterConnectError( 'SQLite database file is not readable' );
155 } elseif ( !in_array( $this->trxMode, self::$VALID_TRX_MODES, true ) ) {
156 throw $this->newExceptionAfterConnectError( "Got mode '{$this->trxMode}' for BEGIN" );
157 }
158
159 $attributes = [];
160 if ( $this->getFlag( self::DBO_PERSISTENT ) ) {
161 // Persistent connections can avoid some schema index reading overhead.
162 // On the other hand, they can cause horrible contention with DBO_TRX.
163 if ( $this->getFlag( self::DBO_TRX ) || $this->getFlag( self::DBO_DEFAULT ) ) {
164 $this->connLogger->warning(
165 __METHOD__ . ": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
166 $this->getLogContext()
167 );
168 } else {
169 $attributes[PDO::ATTR_PERSISTENT] = true;
170 }
171 }
172
173 try {
174 // Open the database file, creating it if it does not yet exist
175 $this->conn = new PDO( "sqlite:$path", null, null, $attributes );
176 } catch ( PDOException $e ) {
177 throw $this->newExceptionAfterConnectError( $e->getMessage() );
178 }
179
180 $this->currentDomain = new DatabaseDomain( $dbName, null, $tablePrefix );
181
182 try {
183 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_NO_RETRY;
184 // Enforce LIKE to be case sensitive, just like MySQL
185 $this->query( 'PRAGMA case_sensitive_like = 1', __METHOD__, $flags );
186 // Apply optimizations or requirements regarding fsync() usage
187 $sync = $this->connectionVariables['synchronous'] ?? null;
188 if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
189 $this->query( "PRAGMA synchronous = $sync", __METHOD__, $flags );
190 }
191 } catch ( Exception $e ) {
192 throw $this->newExceptionAfterConnectError( $e->getMessage() );
193 }
194 }
195
196 /**
197 * @return string|null SQLite DB file path
198 * @throws DBUnexpectedError
199 * @since 1.25
200 */
201 public function getDbFilePath() {
202 return $this->dbPath ?? self::generateFileName( $this->dbDir, $this->getDBname() );
203 }
204
205 /**
206 * @return string|null Lock file directory
207 */
208 public function getLockFileDirectory() {
209 if ( $this->dbPath !== null && !self::isProcessMemoryPath( $this->dbPath ) ) {
210 return dirname( $this->dbPath ) . '/locks';
211 } elseif ( $this->dbDir !== null && !self::isProcessMemoryPath( $this->dbDir ) ) {
212 return $this->dbDir . '/locks';
213 }
214
215 return null;
216 }
217
218 /**
219 * Does not actually close the connection, just destroys the reference for GC to do its work
220 * @return bool
221 */
222 protected function closeConnection() {
223 $this->conn = null;
224
225 return true;
226 }
227
228 /**
229 * Generates a database file name. Explicitly public for installer.
230 * @param string $dir Directory where database resides
231 * @param string|bool $dbName Database name (or false from Database::factory, validated here)
232 * @return string
233 * @throws DBUnexpectedError
234 */
235 public static function generateFileName( $dir, $dbName ) {
236 if ( $dir == '' ) {
237 throw new DBUnexpectedError( null, __CLASS__ . ": no DB directory specified" );
238 } elseif ( self::isProcessMemoryPath( $dir ) ) {
239 throw new DBUnexpectedError(
240 null,
241 __CLASS__ . ": cannot use process memory directory '$dir'"
242 );
243 } elseif ( !strlen( $dbName ) ) {
244 throw new DBUnexpectedError( null, __CLASS__ . ": no DB name specified" );
245 }
246
247 return "$dir/$dbName.sqlite";
248 }
249
250 /**
251 * @param string $path
252 * @return string
253 */
254 private static function generateDatabaseName( $path ) {
255 if ( preg_match( '/^(:memory:$|file::memory:)/', $path ) ) {
256 // E.g. "file::memory:?cache=shared" => ":memory":
257 return ':memory:';
258 } elseif ( preg_match( '/^file::([^?]+)\?mode=memory(&|$)/', $path, $m ) ) {
259 // E.g. "file:memdb1?mode=memory" => ":memdb1:"
260 return ":{$m[1]}:";
261 } else {
262 // E.g. "/home/.../some_db.sqlite3" => "some_db"
263 return preg_replace( '/\.sqlite\d?$/', '', basename( $path ) );
264 }
265 }
266
267 /**
268 * @param string $path
269 * @return bool
270 */
271 private static function isProcessMemoryPath( $path ) {
272 return preg_match( '/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/', $path );
273 }
274
275 /**
276 * Returns version of currently supported SQLite fulltext search module or false if none present.
277 * @return string
278 */
279 static function getFulltextSearchModule() {
280 static $cachedResult = null;
281 if ( $cachedResult !== null ) {
282 return $cachedResult;
283 }
284 $cachedResult = false;
285 $table = 'dummy_search_test';
286
287 $db = self::newStandaloneInstance( ':memory:' );
288 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
289 $cachedResult = 'FTS3';
290 }
291 $db->close();
292
293 return $cachedResult;
294 }
295
296 /**
297 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
298 * for details.
299 *
300 * @param string $name Database name to be used in queries like
301 * SELECT foo FROM dbname.table
302 * @param bool|string $file Database file name. If omitted, will be generated
303 * using $name and configured data directory
304 * @param string $fname Calling function name
305 * @return IResultWrapper
306 */
307 public function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
308 $file = is_string( $file ) ? $file : self::generateFileName( $this->dbDir, $name );
309 $encFile = $this->addQuotes( $file );
310
311 return $this->query(
312 "ATTACH DATABASE $encFile AS $name",
313 $fname,
314 self::QUERY_IGNORE_DBO_TRX
315 );
316 }
317
318 protected function isWriteQuery( $sql ) {
319 return parent::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
320 }
321
322 protected function isTransactableQuery( $sql ) {
323 return parent::isTransactableQuery( $sql ) && !in_array(
324 $this->getQueryVerb( $sql ),
325 [ 'ATTACH', 'PRAGMA' ],
326 true
327 );
328 }
329
330 /**
331 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
332 *
333 * @param string $sql
334 * @return bool|IResultWrapper
335 */
336 protected function doQuery( $sql ) {
337 $res = $this->getBindingHandle()->query( $sql );
338 if ( $res === false ) {
339 return false;
340 }
341
342 $resource = ResultWrapper::unwrap( $res );
343 $this->lastAffectedRowCount = $resource->rowCount();
344 $res = new ResultWrapper( $this, $resource->fetchAll() );
345
346 return $res;
347 }
348
349 /**
350 * @param IResultWrapper|mixed $res
351 */
352 function freeResult( $res ) {
353 if ( $res instanceof ResultWrapper ) {
354 $res->free();
355 }
356 }
357
358 /**
359 * @param IResultWrapper|array $res
360 * @return stdClass|bool
361 */
362 function fetchObject( $res ) {
363 $resource =& ResultWrapper::unwrap( $res );
364
365 $cur = current( $resource );
366 if ( is_array( $cur ) ) {
367 next( $resource );
368 $obj = new stdClass;
369 foreach ( $cur as $k => $v ) {
370 if ( !is_numeric( $k ) ) {
371 $obj->$k = $v;
372 }
373 }
374
375 return $obj;
376 }
377
378 return false;
379 }
380
381 /**
382 * @param IResultWrapper|mixed $res
383 * @return array|bool
384 */
385 function fetchRow( $res ) {
386 $resource =& ResultWrapper::unwrap( $res );
387 $cur = current( $resource );
388 if ( is_array( $cur ) ) {
389 next( $resource );
390
391 return $cur;
392 }
393
394 return false;
395 }
396
397 /**
398 * The PDO::Statement class implements the array interface so count() will work
399 *
400 * @param IResultWrapper|array|false $res
401 * @return int
402 */
403 function numRows( $res ) {
404 // false does not implement Countable
405 $resource = ResultWrapper::unwrap( $res );
406
407 return is_array( $resource ) ? count( $resource ) : 0;
408 }
409
410 /**
411 * @param IResultWrapper $res
412 * @return int
413 */
414 function numFields( $res ) {
415 $resource = ResultWrapper::unwrap( $res );
416 if ( is_array( $resource ) && count( $resource ) > 0 ) {
417 // The size of the result array is twice the number of fields. (T67578)
418 return count( $resource[0] ) / 2;
419 } else {
420 // If the result is empty return 0
421 return 0;
422 }
423 }
424
425 /**
426 * @param IResultWrapper $res
427 * @param int $n
428 * @return bool
429 */
430 function fieldName( $res, $n ) {
431 $resource = ResultWrapper::unwrap( $res );
432 if ( is_array( $resource ) ) {
433 $keys = array_keys( $resource[0] );
434
435 return $keys[$n];
436 }
437
438 return false;
439 }
440
441 protected function doSelectDomain( DatabaseDomain $domain ) {
442 if ( $domain->getSchema() !== null ) {
443 throw new DBExpectedError(
444 $this,
445 __CLASS__ . ": domain '{$domain->getId()}' has a schema component"
446 );
447 }
448
449 $database = $domain->getDatabase();
450 // A null database means "don't care" so leave it as is and update the table prefix
451 if ( $database === null ) {
452 $this->currentDomain = new DatabaseDomain(
453 $this->currentDomain->getDatabase(),
454 null,
455 $domain->getTablePrefix()
456 );
457
458 return true;
459 }
460
461 if ( $database !== $this->getDBname() ) {
462 throw new DBExpectedError(
463 $this,
464 __CLASS__ . ": cannot change database (got '$database')"
465 );
466 }
467
468 return true;
469 }
470
471 /**
472 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
473 *
474 * @param string $name
475 * @param string $format
476 * @return string
477 */
478 function tableName( $name, $format = 'quoted' ) {
479 // table names starting with sqlite_ are reserved
480 if ( strpos( $name, 'sqlite_' ) === 0 ) {
481 return $name;
482 }
483
484 return str_replace( '"', '', parent::tableName( $name, $format ) );
485 }
486
487 /**
488 * This must be called after nextSequenceVal
489 *
490 * @return int
491 */
492 function insertId() {
493 // PDO::lastInsertId yields a string :(
494 return intval( $this->getBindingHandle()->lastInsertId() );
495 }
496
497 /**
498 * @param IResultWrapper|array $res
499 * @param int $row
500 */
501 function dataSeek( $res, $row ) {
502 $resource =& ResultWrapper::unwrap( $res );
503 reset( $resource );
504 if ( $row > 0 ) {
505 for ( $i = 0; $i < $row; $i++ ) {
506 next( $resource );
507 }
508 }
509 }
510
511 /**
512 * @return string
513 */
514 function lastError() {
515 if ( !is_object( $this->conn ) ) {
516 return "Cannot return last error, no db connection";
517 }
518 $e = $this->conn->errorInfo();
519
520 return $e[2] ?? '';
521 }
522
523 /**
524 * @return string
525 */
526 function lastErrno() {
527 if ( !is_object( $this->conn ) ) {
528 return "Cannot return last error, no db connection";
529 } else {
530 $info = $this->conn->errorInfo();
531
532 return $info[1];
533 }
534 }
535
536 /**
537 * @return int
538 */
539 protected function fetchAffectedRowCount() {
540 return $this->lastAffectedRowCount;
541 }
542
543 function tableExists( $table, $fname = __METHOD__ ) {
544 $tableRaw = $this->tableName( $table, 'raw' );
545 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
546 return true; // already known to exist
547 }
548
549 $encTable = $this->addQuotes( $tableRaw );
550 $res = $this->query(
551 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
552 __METHOD__,
553 self::QUERY_IGNORE_DBO_TRX
554 );
555
556 return $res->numRows() ? true : false;
557 }
558
559 /**
560 * Returns information about an index
561 * Returns false if the index does not exist
562 * - if errors are explicitly ignored, returns NULL on failure
563 *
564 * @param string $table
565 * @param string $index
566 * @param string $fname
567 * @return array|false
568 */
569 function indexInfo( $table, $index, $fname = __METHOD__ ) {
570 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
571 $res = $this->query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX );
572 if ( !$res || $res->numRows() == 0 ) {
573 return false;
574 }
575 $info = [];
576 foreach ( $res as $row ) {
577 $info[] = $row->name;
578 }
579
580 return $info;
581 }
582
583 /**
584 * @param string $table
585 * @param string $index
586 * @param string $fname
587 * @return bool|null
588 */
589 function indexUnique( $table, $index, $fname = __METHOD__ ) {
590 $row = $this->selectRow( 'sqlite_master', '*',
591 [
592 'type' => 'index',
593 'name' => $this->indexName( $index ),
594 ], $fname );
595 if ( !$row || !isset( $row->sql ) ) {
596 return null;
597 }
598
599 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
600 $indexPos = strpos( $row->sql, 'INDEX' );
601 if ( $indexPos === false ) {
602 return null;
603 }
604 $firstPart = substr( $row->sql, 0, $indexPos );
605 $options = explode( ' ', $firstPart );
606
607 return in_array( 'UNIQUE', $options );
608 }
609
610 /**
611 * Filter the options used in SELECT statements
612 *
613 * @param array $options
614 * @return array
615 */
616 function makeSelectOptions( $options ) {
617 foreach ( $options as $k => $v ) {
618 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' || $v == 'LOCK IN SHARE MODE' ) ) {
619 $options[$k] = '';
620 }
621 }
622
623 return parent::makeSelectOptions( $options );
624 }
625
626 /**
627 * @param array $options
628 * @return array
629 */
630 protected function makeUpdateOptionsArray( $options ) {
631 $options = parent::makeUpdateOptionsArray( $options );
632 $options = self::fixIgnore( $options );
633
634 return $options;
635 }
636
637 /**
638 * @param array $options
639 * @return array
640 */
641 static function fixIgnore( $options ) {
642 # SQLite uses OR IGNORE not just IGNORE
643 foreach ( $options as $k => $v ) {
644 if ( $v == 'IGNORE' ) {
645 $options[$k] = 'OR IGNORE';
646 }
647 }
648
649 return $options;
650 }
651
652 /**
653 * @param array $options
654 * @return string
655 */
656 function makeInsertOptions( $options ) {
657 $options = self::fixIgnore( $options );
658
659 return parent::makeInsertOptions( $options );
660 }
661
662 /**
663 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
664 * @param string $table
665 * @param array $a
666 * @param string $fname
667 * @param array $options
668 * @return bool
669 */
670 function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
671 if ( !count( $a ) ) {
672 return true;
673 }
674
675 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
676 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
677 $affectedRowCount = 0;
678 try {
679 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
680 foreach ( $a as $v ) {
681 parent::insert( $table, $v, "$fname/multi-row", $options );
682 $affectedRowCount += $this->affectedRows();
683 }
684 $this->endAtomic( $fname );
685 } catch ( Exception $e ) {
686 $this->cancelAtomic( $fname );
687 throw $e;
688 }
689 $this->affectedRowCount = $affectedRowCount;
690 } else {
691 parent::insert( $table, $a, "$fname/single-row", $options );
692 }
693
694 return true;
695 }
696
697 /**
698 * @param string $table
699 * @param array $uniqueIndexes Unused
700 * @param string|array $rows
701 * @param string $fname
702 */
703 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
704 if ( !count( $rows ) ) {
705 return;
706 }
707
708 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
709 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
710 $affectedRowCount = 0;
711 try {
712 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
713 foreach ( $rows as $v ) {
714 $this->nativeReplace( $table, $v, "$fname/multi-row" );
715 $affectedRowCount += $this->affectedRows();
716 }
717 $this->endAtomic( $fname );
718 } catch ( Exception $e ) {
719 $this->cancelAtomic( $fname );
720 throw $e;
721 }
722 $this->affectedRowCount = $affectedRowCount;
723 } else {
724 $this->nativeReplace( $table, $rows, "$fname/single-row" );
725 }
726 }
727
728 /**
729 * Returns the size of a text field, or -1 for "unlimited"
730 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
731 *
732 * @param string $table
733 * @param string $field
734 * @return int
735 */
736 function textFieldSize( $table, $field ) {
737 return -1;
738 }
739
740 /**
741 * @return bool
742 */
743 function unionSupportsOrderAndLimit() {
744 return false;
745 }
746
747 /**
748 * @param string[] $sqls
749 * @param bool $all Whether to "UNION ALL" or not
750 * @return string
751 */
752 function unionQueries( $sqls, $all ) {
753 $glue = $all ? ' UNION ALL ' : ' UNION ';
754
755 return implode( $glue, $sqls );
756 }
757
758 /**
759 * @return bool
760 */
761 function wasDeadlock() {
762 return $this->lastErrno() == 5; // SQLITE_BUSY
763 }
764
765 /**
766 * @return bool
767 */
768 function wasReadOnlyError() {
769 return $this->lastErrno() == 8; // SQLITE_READONLY;
770 }
771
772 public function wasConnectionError( $errno ) {
773 return $errno == 17; // SQLITE_SCHEMA;
774 }
775
776 protected function wasKnownStatementRollbackError() {
777 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
778 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
779 // https://sqlite.org/lang_createtable.html#uniqueconst
780 // https://sqlite.org/lang_conflict.html
781 return false;
782 }
783
784 public function serverIsReadOnly() {
785 $this->assertHasConnectionHandle();
786
787 $path = $this->getDbFilePath();
788
789 return ( !self::isProcessMemoryPath( $path ) && !is_writable( $path ) );
790 }
791
792 /**
793 * @return string Wikitext of a link to the server software's web site
794 */
795 public function getSoftwareLink() {
796 return "[{{int:version-db-sqlite-url}} SQLite]";
797 }
798
799 /**
800 * @return string Version information from the database
801 */
802 function getServerVersion() {
803 $ver = $this->getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
804
805 return $ver;
806 }
807
808 /**
809 * Get information about a given field
810 * Returns false if the field does not exist.
811 *
812 * @param string $table
813 * @param string $field
814 * @return SQLiteField|bool False on failure
815 */
816 function fieldInfo( $table, $field ) {
817 $tableName = $this->tableName( $table );
818 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
819 $res = $this->query( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
820 foreach ( $res as $row ) {
821 if ( $row->name == $field ) {
822 return new SQLiteField( $row, $tableName );
823 }
824 }
825
826 return false;
827 }
828
829 protected function doBegin( $fname = '' ) {
830 if ( $this->trxMode != '' ) {
831 $this->query( "BEGIN {$this->trxMode}", $fname );
832 } else {
833 $this->query( 'BEGIN', $fname );
834 }
835 }
836
837 /**
838 * @param string $s
839 * @return string
840 */
841 function strencode( $s ) {
842 return substr( $this->addQuotes( $s ), 1, -1 );
843 }
844
845 /**
846 * @param string $b
847 * @return Blob
848 */
849 function encodeBlob( $b ) {
850 return new Blob( $b );
851 }
852
853 /**
854 * @param Blob|string $b
855 * @return string
856 */
857 function decodeBlob( $b ) {
858 if ( $b instanceof Blob ) {
859 $b = $b->fetch();
860 }
861
862 return $b;
863 }
864
865 /**
866 * @param string|int|null|bool|Blob $s
867 * @return string|int
868 */
869 function addQuotes( $s ) {
870 if ( $s instanceof Blob ) {
871 return "x'" . bin2hex( $s->fetch() ) . "'";
872 } elseif ( is_bool( $s ) ) {
873 return (int)$s;
874 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
875 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
876 // This is a known limitation of SQLite's mprintf function which PDO
877 // should work around, but doesn't. I have reported this to php.net as bug #63419:
878 // https://bugs.php.net/bug.php?id=63419
879 // There was already a similar report for SQLite3::escapeString, bug #62361:
880 // https://bugs.php.net/bug.php?id=62361
881 // There is an additional bug regarding sorting this data after insert
882 // on older versions of sqlite shipped with ubuntu 12.04
883 // https://phabricator.wikimedia.org/T74367
884 $this->queryLogger->debug(
885 __FUNCTION__ .
886 ': Quoting value containing null byte. ' .
887 'For consistency all binary data should have been ' .
888 'first processed with self::encodeBlob()'
889 );
890 return "x'" . bin2hex( (string)$s ) . "'";
891 } else {
892 return $this->getBindingHandle()->quote( (string)$s );
893 }
894 }
895
896 public function buildSubstring( $input, $startPosition, $length = null ) {
897 $this->assertBuildSubstringParams( $startPosition, $length );
898 $params = [ $input, $startPosition ];
899 if ( $length !== null ) {
900 $params[] = $length;
901 }
902 return 'SUBSTR(' . implode( ',', $params ) . ')';
903 }
904
905 /**
906 * @param string $field Field or column to cast
907 * @return string
908 * @since 1.28
909 */
910 public function buildStringCast( $field ) {
911 return 'CAST ( ' . $field . ' AS TEXT )';
912 }
913
914 /**
915 * No-op version of deadlockLoop
916 *
917 * @return mixed
918 */
919 public function deadlockLoop( /*...*/ ) {
920 $args = func_get_args();
921 $function = array_shift( $args );
922
923 return $function( ...$args );
924 }
925
926 /**
927 * @param string $s
928 * @return string
929 */
930 protected function replaceVars( $s ) {
931 $s = parent::replaceVars( $s );
932 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
933 // CREATE TABLE hacks to allow schema file sharing with MySQL
934
935 // binary/varbinary column type -> blob
936 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
937 // no such thing as unsigned
938 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
939 // INT -> INTEGER
940 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
941 // floating point types -> REAL
942 $s = preg_replace(
943 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
944 'REAL',
945 $s
946 );
947 // varchar -> TEXT
948 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
949 // TEXT normalization
950 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
951 // BLOB normalization
952 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
953 // BOOL -> INTEGER
954 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
955 // DATETIME -> TEXT
956 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
957 // No ENUM type
958 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
959 // binary collation type -> nothing
960 $s = preg_replace( '/\bbinary\b/i', '', $s );
961 // auto_increment -> autoincrement
962 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
963 // No explicit options
964 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
965 // AUTOINCREMENT should immedidately follow PRIMARY KEY
966 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
967 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
968 // No truncated indexes
969 $s = preg_replace( '/\(\d+\)/', '', $s );
970 // No FULLTEXT
971 $s = preg_replace( '/\bfulltext\b/i', '', $s );
972 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
973 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
974 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
975 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
976 // INSERT IGNORE --> INSERT OR IGNORE
977 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
978 }
979
980 return $s;
981 }
982
983 public function lock( $lockName, $method, $timeout = 5 ) {
984 $status = $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout );
985 if (
986 $this->lockMgr instanceof FSLockManager &&
987 $status->hasMessage( 'lockmanager-fail-openlock' )
988 ) {
989 throw new DBError( $this, "Cannot create directory \"{$this->getLockFileDirectory()}\"" );
990 }
991
992 return $status->isOK();
993 }
994
995 public function unlock( $lockName, $method ) {
996 return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isGood();
997 }
998
999 /**
1000 * Build a concatenation list to feed into a SQL query
1001 *
1002 * @param string[] $stringList
1003 * @return string
1004 */
1005 function buildConcat( $stringList ) {
1006 return '(' . implode( ') || (', $stringList ) . ')';
1007 }
1008
1009 public function buildGroupConcatField(
1010 $delim, $table, $field, $conds = '', $join_conds = []
1011 ) {
1012 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
1013
1014 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1015 }
1016
1017 /**
1018 * @param string $oldName
1019 * @param string $newName
1020 * @param bool $temporary
1021 * @param string $fname
1022 * @return bool|IResultWrapper
1023 * @throws RuntimeException
1024 */
1025 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1026 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
1027 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
1028 $obj = $this->fetchObject( $res );
1029 if ( !$obj ) {
1030 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1031 }
1032 $sql = $obj->sql;
1033 $sql = preg_replace(
1034 '/(?<=\W)"?' .
1035 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1036 '"?(?=\W)/',
1037 $this->addIdentifierQuotes( $newName ),
1038 $sql,
1039 1
1040 );
1041 if ( $temporary ) {
1042 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1043 $this->queryLogger->debug(
1044 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1045 } else {
1046 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1047 }
1048 }
1049
1050 $res = $this->query( $sql, $fname, self::QUERY_PSEUDO_PERMANENT );
1051
1052 // Take over indexes
1053 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1054 foreach ( $indexList as $index ) {
1055 if ( strpos( $index->name, 'sqlite_autoindex' ) === 0 ) {
1056 continue;
1057 }
1058
1059 if ( $index->unique ) {
1060 $sql = 'CREATE UNIQUE INDEX';
1061 } else {
1062 $sql = 'CREATE INDEX';
1063 }
1064 // Try to come up with a new index name, given indexes have database scope in SQLite
1065 $indexName = $newName . '_' . $index->name;
1066 $sql .= ' ' . $indexName . ' ON ' . $newName;
1067
1068 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) . ')' );
1069 $fields = [];
1070 foreach ( $indexInfo as $indexInfoRow ) {
1071 $fields[$indexInfoRow->seqno] = $indexInfoRow->name;
1072 }
1073
1074 $sql .= '(' . implode( ',', $fields ) . ')';
1075
1076 $this->query( $sql );
1077 }
1078
1079 return $res;
1080 }
1081
1082 /**
1083 * List all tables on the database
1084 *
1085 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1086 * @param string $fname Calling function name
1087 *
1088 * @return array
1089 */
1090 function listTables( $prefix = null, $fname = __METHOD__ ) {
1091 $result = $this->select(
1092 'sqlite_master',
1093 'name',
1094 "type='table'"
1095 );
1096
1097 $endArray = [];
1098
1099 foreach ( $result as $table ) {
1100 $vars = get_object_vars( $table );
1101 $table = array_pop( $vars );
1102
1103 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1104 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1105 $endArray[] = $table;
1106 }
1107 }
1108 }
1109
1110 return $endArray;
1111 }
1112
1113 /**
1114 * Override due to no CASCADE support
1115 *
1116 * @param string $tableName
1117 * @param string $fName
1118 * @return bool|IResultWrapper
1119 * @throws DBReadOnlyError
1120 */
1121 public function dropTable( $tableName, $fName = __METHOD__ ) {
1122 if ( !$this->tableExists( $tableName, $fName ) ) {
1123 return false;
1124 }
1125 $sql = "DROP TABLE " . $this->tableName( $tableName );
1126
1127 return $this->query( $sql, $fName, self::QUERY_IGNORE_DBO_TRX );
1128 }
1129
1130 public function setTableAliases( array $aliases ) {
1131 parent::setTableAliases( $aliases );
1132 foreach ( $this->tableAliases as $params ) {
1133 if ( isset( $this->alreadyAttached[$params['dbname']] ) ) {
1134 continue;
1135 }
1136 $this->attachDatabase( $params['dbname'] );
1137 $this->alreadyAttached[$params['dbname']] = true;
1138 }
1139 }
1140
1141 public function resetSequenceForTable( $table, $fname = __METHOD__ ) {
1142 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1143 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1144 $this->query(
1145 "DELETE FROM $encTable WHERE name = $encName",
1146 $fname,
1147 self::QUERY_IGNORE_DBO_TRX
1148 );
1149 }
1150
1151 public function databasesAreIndependent() {
1152 return true;
1153 }
1154
1155 /**
1156 * @return PDO
1157 */
1158 protected function getBindingHandle() {
1159 return parent::getBindingHandle();
1160 }
1161 }
1162
1163 /**
1164 * @deprecated since 1.29
1165 */
1166 class_alias( DatabaseSqlite::class, 'DatabaseSqlite' );